package com.springboot.java.design.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: TongRui乀
 * @Date: 2020/7/5 9:45
 * @description：
 */
@Slf4j
public class TestCountDownLatch {

    public static void main(String[] args) {

        test_02();

    }

    /**
     *  一个线程等待多个线程执行完再执行
     */
    public static void test_01(){

        CountDownLatch latch = new CountDownLatch(5);

        ExecutorService executors = Executors.newFixedThreadPool(5);

        for (int i = 0; i < 5; i++) {

            executors.execute(()->{

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                log.info("线程-{}-执行完了", Thread.currentThread().getName());
                latch.countDown();
            });

        }

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        log.info("所有子线程执行完了。。。");

        log.info("我开始执行了");

        executors.shutdown();
    }

    /**
     *  多个线程等待一个线程执行之后执行
     */
    public static void test_02(){
        CountDownLatch latch = new CountDownLatch(1);

        ExecutorService executors = Executors.newFixedThreadPool(5);

        for (int i = 0; i < 5; i++) {

            executors.execute(()->{

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                log.info("线程-{}-准备好了", Thread.currentThread().getName());
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                log.info("线程-{}-执行了", Thread.currentThread().getName());
            });

        }

        try {
            Thread.sleep(6000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        log.info("所有子线程准备好了。。。。。。。。。。。。");
        latch.countDown();

        executors.shutdown();
    }

}

